<!--

/*
* Copyright (C) 2005-2013 University of Sydney
*
* Licensed under the GNU License, Version 3.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.gnu.org/licenses/gpl-3.0.txt
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/

/**
* brief description of file
*
* @author      Tom Murtagh
* @author      Kim Jackson
* @author      Ian Johnson   <ian.johnson@sydney.edu.au>
* @author      Stephen White   <stephen.white@sydney.edu.au>
* @author      Artem Osmakov   <artem.osmakov@sydney.edu.au>
* @copyright   (C) 2005-2013 University of Sydney
* @link        http://Sydney.edu.au/Heurist
* @version     3.1.0
* @license     http://www.gnu.org/licenses/gpl-3.0.txt GNU License 3.0
* @package     Heurist academic knowledge management system
* @subpackage  !!!subpackagename for file such as Administration, Search, Edit, Application, Library
*/

-->
<!--

/**
 * filename, brief description, date of creation, by whom
 * @copyright (C) 2005-2010 University of Sydney Digital Innovation Unit.
 * @link: http://HeuristScholar.org
 * @license http://www.gnu.org/licenses/gpl-3.0.txt
 * @package Heurist academic knowledge management system
 * @todo
 **/

-->
<html>
 <head>
  <link rel="stylesheet" href="../../common/css/global.css">
  <title>Add relationships to selected records</title>

  <style type="text/css">
	#record-count {
		font-weight: bold;
	}
	#relationship-type {
		margin-bottom: 10px;
	}
	#related-record {
		width: 250px;
		border: 1px dotted gray;
		cursor: pointer;
		margin-bottom: 20px;
	}
  </style>
 </head>

 <body class="popup" onload="init();">
  <script type="text/javascript" src="../../external/yui/2.8.2r1/build/yahoo/yahoo-min.js"></script>
  <script type="text/javascript" src="../../external/yui/2.8.2r1/build/json/json-min.js"></script>
  <script src="../../common/js/utilsLoad.js"></script>
  <script src="../../common/php/getMagicNumbers.php"></script>

  <script>

var Hul = top.HEURIST.util;

var relTargetID;
var recCountSpan;
var relTypeSelect;
var relTargetInput;
var hBase = "http://" + window.location.host +
			(top && top.HEURIST && top.HEURIST.basePath? top.HEURIST.basePath : window.location.pathname.match(/^\/[^\/]+\//));
var database = (top && top.HEURIST && top.HEURIST.database? top.HEURIST.database.name : location.search.match(/db=([^&]+)/)[1]);

function init () {

	relTargetID = null;
	recCountSpan = document.getElementById("record-count");
	var relTypeSelectDiv = document.getElementById("relationship-type-div");
	relTargetInput = document.getElementById("related-record");

	recCountSpan.innerHTML = top.HEURIST.search.getSelectedRecIDs().get().length;
	var reltypDT = top.HEURIST.magicNumbers['DT_RELATION_TYPE'];
	var relRT = top.HEURIST.magicNumbers['RT_RELATION'];
	var relTypeTerms = top.HEURIST.rectypes.typedefs[relRT].dtFields[reltypDT][top.HEURIST.rectypes.typedefs.dtFieldNamesToIndex['rst_FilteredJsonTermIDTree']];
	var relTypeTermsDisabled = top.HEURIST.rectypes.typedefs[relRT].dtFields[reltypDT][top.HEURIST.rectypes.typedefs.dtFieldNamesToIndex['rst_TermIDTreeNonSelectableIDs']];

	if(Hul.isempty(relTypeTerms)){
		relTypeTerms = top.HEURIST.detailTypes.typedefs[relRT].commonFields[top.HEURIST.detailTypes.typedefs.fieldNamesToIndex.dty_JsonTermIDTree]
	}
	if(Hul.isempty(relTypeTermsDisabled)){
		relTypeTermsDisabled = top.HEURIST.detailTypes.typedefs[reltypDT].commonFields[top.HEURIST.detailTypes.typedefs.fieldNamesToIndex.dty_TermIDTreeNonSelectableIDs];
	}
	relTypeTerms = Hul.expandJsonStructure(relTypeTerms);
	relTypeTermsDisabled = Hul.expandJsonStructure(relTypeTermsDisabled);

	relTypeSelect = Hul.createTermSelect(relTypeTerms,
													(relTypeTermsDisabled || ""),
													"relation",
													"IsPartOf");
	relTypeSelectDiv.appendChild(relTypeSelect);

	relTargetInput.onclick = selectRelRecord;
	selectRelRecord();
}

function selectRelRecord() {

		//deft="+top.HEURIST.magicNumbers['RT_AGGREGATION']+"

		Hul.popupURL(window, hBase + "records/pointer/selectRecordFromSearch.html?q=&db=" + database, {
			callback: function(recID, recTitle) {
				relTargetInput.value = recID && recTitle ? recTitle : "";
				relTargetID = recID || null;
			}
		});
}

function save () {	// xhrFormSubmit only uses the form's action and elements(name & value) properties
	var fakeForm = {
		action: top.HEURIST.basePath + "records/relationships/saveRelationships.php?db=" + database,
		elements: [
			{ name: "recID", value: top.HEURIST.search.getSelectedRecIDs().get().join(",") },
			{ name: "save-mode", value: "new" },
			{ name: "RelTermID", value: relTypeSelect.value },
			{ name: "RelatedRecID", value: relTargetID }
		]
	};

	Hul.xhrFormSubmit(fakeForm, function(json) {
		var i, l, rels;
		var vals = eval(json.responseText);
		if (! vals) {
			alert("No response from server");
		}
		else if (vals.error) {
			alert("Error while saving:\n" + vals.error);
		} else {
			rels = 0;
			if (vals.length) {
				l = vals.length;
				for (i = 0; i < l; ++i) {
					if (vals[i].relationship) {
						++rels;
					}
				}
			} else if (vals.relationship) {
				rels = 1;
			}
			document.getElementById("status").innerHTML = "<b>" + rels + "</b> relationships added."
//			setTimeout(function () {
//				top.location.href = hBase + "?q=relationsfor:" + relTargetID + "&db=" + database;
//				top.HEURIST.reloadSearch();
//			}, 2000);
			window.close();
		}
	});
}


  </script>

   <p><span id="record-count"></span> selected records</p>

   <div id="relationship-type-div">Relationship type:
   </div>

   <div>
    <label for="related-record">Related Record:</label>
   <input type="text" id="related-record">
   </div>
   <input type="button" value="add relationships" onclick="this.disabled = true; save();">
   <input type="button" value="cancel" onclick="window.close();">

   <p id="status"></p>

 </body>
</html>
